﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace exempelTenta1_uppg5
{
    class HashTable<key, value>
    {
        private Node<key, value> head = null;
        private Node<key, value>[] array;
        int size;

        public HashTable()
        {
            size = 127;
            array = new Node<key, value>[size];
        }

        public HashTable(int size)
        {
            this.size = size;
            array = new Node<key, value>[size];
        }

        public void Add(key k, value v)
        {
            int hash = Math.Abs(k.GetHashCode() % size);
            Node<key, value> insert = new Node<key, value>(k, v);
            array[hash] = insert;

            for (int i = hash - 1; i >= 0; i--)
            {
                if (array[i] != null)
                {
                    Node<key, value> n = array[i];
                    while (n.Next.Key.Equals(n.Key))
                    {
                        n = n.Next;
                    }
                    insert.Next = n.Next;
                    n.Next = insert;
                    return;
                }
            }
            insert.Next = head;
            head = insert;          
        }

        public Node<key, value> Search(key k)
        {
            int hash = Math.Abs(k.GetHashCode() % size);
            return array[hash];
        }

        public void Print()
        {
            foreach (var n in array)
            {
                if(n != null)
                {
                    Console.WriteLine("Hash : " + Math.Abs(n.Key.GetHashCode() % size) + " Key : " + n.Key + " Value : " + n.Value);
                }                
            }
        }

    }
}
